/*
 * zach.cpp
 *
 *   Created on: 2011-9-25
 *       Author: 左白
 *  Description: zach.h实现
 */

#include "zach.h"
#include "util.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <clocale>

namespace zach
{
#if (1) /* UTF-32字符 */
#if WCHAR_MAX > 0xFFFF
inline static wchar_t toWChar( Char c )
{
	return c;
}
#else
inline static wchar_t toWChar( Char c )
{
	return c > 0xFFFF ? ' ' : c;
}
#endif
#endif /* UTF-32字符 */

#if (1) /* String实现 */
String getString( const std::vector<Char>& str )
{
	String retVal;
	retVal._length = str.size(); // 获取长度
	retVal._str = ( Char* ) malloc( sizeof(Char) * retVal._length ); // 分配空间
	memcpy( retVal._str, &str[0], sizeof(Char) * retVal._length ); // 复制内容

	return retVal;
}

String getString( const char* str )
{
	String retVal;

	retVal._length = strlen( str ); // 获取长度
	retVal._str = ( Char* ) malloc( sizeof(Char) * retVal._length ); // 分配空间

	// 复制内容
	for ( int i = 0; i != retVal._length; ++i ) {
		retVal._str[i] = str[i];
	}

	return retVal;
}

String getString( char c )
{
	String retVal;

	retVal._length = 1; // 长度为1
	retVal._str = ( Char* ) malloc( sizeof(Char) ); // 分配空间
	retVal._str[0] = c; // 第一个字符

	return retVal;
}

string toString( const String str )
{
	return toString( str._str, str._length );
}

string toString( const Char* str, int length )
{
	string retVal;
	setlocale( LC_ALL, "" );

	//转换为0结尾wchar_t
	wchar_t* wcs = ( wchar_t* ) malloc( sizeof(wchar_t) * ( length + 1 ) );
	for ( int i = 0; i < length; i++ ) {
		wcs[i] = toWChar( str[i] );
	}
	wcs[length] = 0;

	//开辟缓冲并转换
	char* dest = ( char* ) malloc( sizeof(char) * MB_CUR_MAX * length );
	if ( wcstombs( dest, wcs, MB_CUR_MAX * length ) < 0 ) {
		throw Fault( "toString failed" );
	}

	retVal.append( dest );

	//清理
	free( wcs );
	free( dest );
	return retVal;
}
#endif /* String实现 */
}
